include(['init'], function(){
	declare('PaintMenu');
	
	addOrientationChangedListener(function(o){
		$('#lowerMenu').css('top', window.innerHeight - 65);
	});

	var painted = {};
	var erased  = {};
		
	var paint = function(e){
		var cell = eGrid.getCell(e.x, e.y)
		if( !cell ) return;
		
		if( cell.contents ){
			cell.contents.attr('src', currentTile.attr('src'))
		}else{
			var contents = $(document.createElement('img'));
			contents.attr('src', currentTile.attr('src'));
            contents.attr('imageId', currentTile.attr('imageId'));
			contents.addClass('ftile');
			contents.addClass('l1');
			contents.css('top', (cell.row)*15);
			contents.css('left', (cell.col)*35);
			cell.contents = contents;
			cell.owner.container.append(contents);
		}
		cell.contents.css('display', "");
		
		var key = cell.col + (cell.row-2)*100+"|"+cell.owner.roomId;
		painted[key] = {row:cell.row-2, col:cell.col,roomId:cell.owner.roomId,imageId:currentTile.attr('imageId')};
		if( erased[key] )
			erased[key] = null;
	};
	
	var erase = function(e){
		var cell = eGrid.getCell(e.x, e.y)
		if( !cell ) return;
		
		if( cell.contents ){
			cell.contents.css('display', "none");
		}
		var key = cell.col + (cell.row-2)*100+"|"+cell.owner.roomId;
		if( painted[key] )
			painted[key] = null;
		erased[key] = {row:cell.row-2, col:cell.col,roomId:cell.owner.roomId,erased:true};
	};
	
	var layerMove = function(e){
		var MAX = 1000;
		var sX = e.bId.lastX || e.bId.x;
		var sY = e.bId.lastY || e.bId.y;
		
		var moveX = e.x-sX;
		moveX = Math.abs(moveX) > MAX ? MAX*(moveX/Math.abs(moveX)) : moveX;
		var moveY = e.y-sY;
		moveY = Math.abs(moveY) > MAX ? MAX*(moveY/Math.abs(moveY)) : moveY;
		
		e.bId.lastX = e.x;
		e.bId.lastY = e.y;
		
		eGrid.translate(moveX, moveY);
	};
		
	var currentMethod = null;

	inputManager.addListener("paintMenu", {
        hidePaintMenu : function(){
            $('#lowerMenu').hide();
            inputManager.lock(null);
            currentMethod = null;
            if( tileSelector ) tileSelector.remove();
            tileSelector = null;
            $('.loaded-cell').each(function(){
                $(this).removeClass('edit-grid');
            });
        },
        showPaintMenu : function(){
            $('#lowerMenu').load(baseUrl+'menu/paint', function(){
                $('#lowerMenu').show();
                $('#lowerMenu').width('95%');
                inputManager.lock('paintMenu');
                currentMethod = layerMove;
                attachMenuListeners();
            });
        },
        onButtonDown : function(e){
            this.onMove(e);
        },
        onMove : function(e){
            if(e.bId && currentMethod) currentMethod(e);
        },
        onMenu : function(e){
            if( e.bId == 'paintButton'){
                if( e.buttons )
                    this.hidePaintMenu();
                else
                    this.showPaintMenu();
            }
        }
	});
	
	var tileSelector = null;
		
	var currentTile  = null;
	
	var attachMenuListeners = function(){
		currentTile = $("#currentTile > span");
		$("#currentTile").click(function(){
			if( currentTile.attr('active')){
				currentTile.attr('active', '');
				currentTile.css('-webkit-opacity', '.5');
				currentMethod = layerMove;
			}else{
				currentTile.attr('active', 'true');
				currentTile.css('-webkit-opacity', '');
				currentMethod = paint;			
			}
		});
		
		$('#actionPaint').click(function(){
			if( !tileSelector ){
				var div = $(document.createElement('div'));
				div.css('position', 'absolute');
				div.css('top', -100);
				div.css('left', 5);
				div.css('background', 'white');
				div.css('z-index', '2000');
				var url = baseUrl + "ui/imageManager"
				div.load(url, function(){
					$('.imageWindow > div > div', div).click(function(){
                        var img = $('img', this);
						var src = img.attr('src');
                        var imageId = img.attr('imageId');
						currentTile.css('background-image', "url('"+src+"')");
						currentTile.attr('src', src);
                        currentTile.attr('imageId', imageId);
						currentTile.attr('active', 'true');
						currentTile.css('-webkit-opacity', '');
						tileSelector.hide();
						currentMethod = paint;
					});
				});
				$('#lowerMenu').append( div );
				$('.loaded-cell').each(function(){
					$(this).addClass('edit-grid');
				});
				tileSelector = div;
			}else{
				tileSelector.show();
			}
			currentMethod = layerMove;
		});
		
		$('#actionErase').click(function(){
			$('.loaded-cell').each(function(){
				$(this).addClass('edit-grid');
			});		
			currentMethod = erase;
		});
		var __menuScope = this;
		$('#actionSave').click(function(){
			$('#spinner').show();
			$.ajax({
				url: roomUrl + '/update/'
				,type : "POST"
				,dataType : 'json'
				,data     : {tiles:JSON.stringify(painted), erased:JSON.stringify(erased)}
				,async    :true
				,beforeSend : function(x){
					if( x && x.overrideMimeType){
						x.overrideMimeType("application/j-son;charset=UTF-8");
					}
				}
				,success  : function(msg){
					painted = {};
					erased  = {};
					$('#spinner').hide();
				}
			});
		});
	}
		
})